package com.eco.fanliapp.job.goodsfree;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.HDKUtils;
import com.eco.fanliapp.service.IAppGoodsService;
import com.eco.fanliapp.service.IUserCashschemeService;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.respone.DTKResponse;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @date 2019-12-01
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class GoodsFreeIntegralTask implements Job, Serializable {
    @Autowired
    private IAppGoodsService iAppGoodsService;
    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private GoodsFreeMapper goodsFreeMapper;
    @Autowired
    private SyChannelGoodsMapper syChannelGoodsMapper;
    @Autowired
    private SyTljGoodsfreeMapper syTljGoodsfreeMapper;
    @Autowired
    private GoodsFreeIntegralMapper goodsFreeIntegralMapper;


    private static final Logger log = LoggerFactory.getLogger(GoodsFreeIntegralTask.class);

    public GoodsFreeIntegralTask() {
    }

    @Override
    public void execute(JobExecutionContext context) {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行拉取积分列表商品定时扫描任务-GoodsFreeTask：executeCount=" + executeCount + "--startTime=" + startTime);


        //从大淘客拉取免单商品
        //跳过 教材、教程、试题
        String pageId = "1";
        String pageSize = "100";
        while (true) {
            try {
                String result = daTaoKeItemInfoService.getGoodsFreeList(pageSize, pageId);
                result = JSONObject.parseObject(result).getString("data");
                if (result == null) {
                    break;
                }
                String pageid = JSONObject.parseObject(result).getString("pageId");
                JSONArray array = JSONArray.parseArray(JSONObject.parseObject(result).getString("list"));
                List<DTKResponse.DataBean> dtkResponse = JsonUtils.getJsonToList(array.toJSONString(), DTKResponse.DataBean.class);
                if (dtkResponse == null || dtkResponse.size() <= 0) {
                    break;
                }
                AppCompany com = userCashschemeService.findCompanyAll();
                for (DTKResponse.DataBean dataBean : dtkResponse) {
                    if (dataBean != null && Double.valueOf(dataBean.getActualPrice()) <= 7D && Double.valueOf(dataBean.getCommissionRate()) >= 70D) {
                        if (dataBean.getTitle().contains("年级") || dataBean.getTitle().contains("编程") || dataBean.getTitle().contains("教学") || dataBean.getTitle().contains("试题") || dataBean.getTitle().contains("微信") || dataBean.getTitle().contains("流量")
                                || dataBean.getTitle().contains("作文") || dataBean.getTitle().contains("教程") || dataBean.getTitle().contains("注册") || dataBean.getTitle().contains("视频") || dataBean.getTitle().contains("考试")
                                || dataBean.getTitle().contains("基础") || dataBean.getTitle().contains("拼音") || dataBean.getTitle().contains("试卷")) {
                            continue;
                        }
                        AppGoods goods = HDKUtils.getAppGoodsFromDTK(dataBean);
                        goods = iAppGoodsService.getMoneyInfoByGoodsId(com, goods);
                        //判断是否最终金额小于0
                        BigDecimal itemendprice = new BigDecimal(goods.getItemendprice() == null ? 0d : goods.getItemendprice());
                        BigDecimal tkMoney = new BigDecimal(goods.getTkmoney() == null ? "0" : goods.getTkmoney());
                        if ((itemendprice.subtract(tkMoney)).compareTo(new BigDecimal(0)) < 0) {
                            continue;
                        }
                        if (goods.getItemendprice() > 7D || goods.getItemendprice() < 5D) {
                            continue;
                        }
                        goods.setItemTop(9);
                        goods.setTaobaoImage(goods.getTaobaoImage() == null ? goods.getItempic() : goods.getTaobaoImage().replace(" ", ""));
                        goods.setCreateTime(DateUtils.getNowTimestamp());
                        goods.setUpdateTime(DateUtils.getNowTimestamp());

                        //判断商品是否存在淘礼金,高佣中
                        SyChannelGoods syChannelGoods = syChannelGoodsMapper.selectChannelGoodsById(Long.valueOf(goods.getItemid()));
                        SyTljGoodsfree syTljGoodsfree = syTljGoodsfreeMapper.selectTljGoodsfreeByItemId(Long.valueOf(goods.getItemid()));
                        HashMap<String, Object> goodsFreeMap = new HashMap<>();
                        goodsFreeMap.put("goodsId", goods.getItemid());
                        goodsFreeMap.put("goodsStatus", 2);
                        List<GoodsFree> goodsFree = goodsFreeMapper.selectByGoodsIds(goodsFreeMap);
                        if (syTljGoodsfree != null && DateUtils.date2Strday(syTljGoodsfree.getUpdateTime()).equals(DateUtils.date2Strday(new Date())) || syChannelGoods != null || goodsFree.size() > 0) {
                            continue;
                        }
                        GoodsFreeIntegral goodsIntegral = goodsFreeIntegralMapper.selectByGoodsId(Long.valueOf(goods.getItemid()));
                        if (goodsIntegral != null) {
                            continue;
                        }
                        int i = addGoodsFreeIntegral(goods);
                        if (i == 1) {
                            log.info("添加商品成功");
                        }
                    }
                }
                pageId = pageid;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("执行拉取积分列表商品定时扫描任务错误");
                break;
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行拉取积分列表商品定时扫描任务-GoodsFreeTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }

    public int addGoodsFreeIntegral(AppGoods goods) {

        AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(goods.getItemid());
        //保存到积分列表表中
        GoodsFreeIntegral goodsFreeIntegral = new GoodsFreeIntegral();
        //默认总公司
        goodsFreeIntegral.setCompanyId(1);
        //默认平台淘宝
        if ("B".equals(goods.getShoptype())) {
            goodsFreeIntegral.setGoodsPlatform(1);
        }
        if ("C".equals(goods.getShoptype())) {
            goodsFreeIntegral.setGoodsPlatform(0);
        }
        goodsFreeIntegral.setItemPrice(goods.getItemprice());
        goodsFreeIntegral.setGoodsId(goods.getItemid());
        goodsFreeIntegral.setGoodsTitle(goods.getItemshorttitle());
        goodsFreeIntegral.setBeginTime(DateFormatUtils.dateToLong(new Date()));
        goodsFreeIntegral.setEndTime(DateFormatUtils.dateToLong(DateFormatUtils.addDate(new Date(), 3)));
        goodsFreeIntegral.setFixedAmount(goods.getItemendprice());
        goodsFreeIntegral.setGoodsPictureUrl(goods.getItempic());
        goodsFreeIntegral.setNumber(goods.getItemsale());
        if (goods.getItemendprice() != null) {
            Integer price = goods.getItemendprice().intValue();
            if (goods.getItemendprice() > price) {
                goodsFreeIntegral.setIntegralNumber(price + 1);
            } else {
                goodsFreeIntegral.setIntegralNumber(price);
            }
        }
        goodsFreeIntegral.setGoodsName(goods.getItemshorttitle());
        goodsFreeIntegral.setGoodsPictureUrl(goods.getItempic());
        goodsFreeIntegral.setPrintUrl(goodsFreeIntegral.getPrintUrl() == null ? goods.getItempic() : goodsFreeIntegral.getPrintUrl());
        int insert = goodsFreeIntegralMapper.insert(goodsFreeIntegral);
        if (appGoods != null) {
            appGoods.setItemTop(9);
            appGoods.setTkmoney(String.valueOf(goodsFreeIntegral.getFixedAmount()));
            appGoods.setItempic(goodsFreeIntegral.getPrintUrl());
            appGoods.setItemtitle(goodsFreeIntegral.getGoodsName());
            appGoods.setItemshorttitle(goodsFreeIntegral.getGoodsName());
            appGoodsMapper.updateAppGoods(appGoods);
        } else {
            int i = appGoodsMapper.insertAppGoods(goods);
            if (i > 0) {
                log.info("添加商品成功");
            }
        }
        if (insert == 1) {
            log.info("数据增加成功");
            return 1;
        } else {
            log.info("数据增加失败");
            return 0;
        }
    }
}
